package cn.itcast.tanhua.sso.controller;

import cn.itcast.tanhua.sso.service.SmsService;
import cn.itcast.tanhua.sso.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @ClassName SmsController
 * @Description 发送短信验证码接口
 * @Author WU
 * @Date 2021/5/24 19:51
 * @Version 1.0
 */
@RestController
@RequestMapping("user")
@Slf4j
public class SmsController {

//    注入SmsService对象
    @Autowired
    private SmsService smsService;

    /**
    * @Description: 定义发送短信验证码接口
    * @Param: 用map对象接收前端信息：手机号
    * @return: 返回一个封装好的结果类对象
    */
    @PostMapping("login")
    public ResponseEntity<ErrorResult> sendCheckCode(@RequestBody Map<String,String> param){
        ErrorResult errorResult=null;
//        获取前端的手机参数
        String phone = param.get("phone");
        try {
//        发送验证码前应该判断该手机号之前是否发过验证码且在有效期内
            errorResult =this.smsService.sendCheckCode(phone);
//        如果返回值为null，则说明此时该手机号在redis中没有有效的验证码
            if (null == errorResult) {
    //            核实成功，返回结果
                return ResponseEntity.ok(null);
            }
        } catch (Exception e) {
//            发送失败则记录日志
            log.error("发送短信验证码失败~ phone = " + phone,e);
//            编辑失败的返回结果
            errorResult = ErrorResult.builder().errCode("000002").errMessage("短信验证码发送失败！").build();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);

    }

}
